import React, {Component} from "react";
import {connect} from "react-redux";
import {history} from "../../App";

class ProductDetail extends Component {

    constructor(props) {
        super(props);
        const {pathname} = window.location;
        this.id = pathname.substr(pathname.lastIndexOf("/") + 1);
    }

    componentDidMount() {
        this.loadData();
    }

    loadData = () => {
        const {dispatch} = this.props;
        dispatch({
            type: "products/detail",
            payload: this.id
        });
    }

    toList = () => {
        history.push("/product");
    }

    render() {
        if (!this.props.product.id || this.id !== this.props.product.id) {
            return null;
        }
        return (
            <div style={{padding: "10px"}}>
                <input type="hidden" name="id" value={this.props.product.id} readOnly={true}/>
                <label htmlFor="txtName">名称: </label>
                <input id="txtName" type="text" name="name" value={this.props.product.name} readOnly={true}/>
                <br/><br/>
                <label htmlFor="txtPrice">价格: </label>
                <input id="txtPrice" type="text" name="price" value={this.props.product.price} readOnly={true}/>
                <br/><br/>
                <button onClick={this.toList}>返回</button>
            </div>
        );
    }
}

const productState = ({products}) => ({...products});

export default connect(productState)(ProductDetail);